// 游戏元素
const startScreen = document.getElementById('start-screen');
const gameScreen = document.getElementById('game-screen');
const pauseScreen = document.getElementById('pause-screen');
const endScreen = document.getElementById('end-screen');
const gameArea = document.getElementById('game-area');
const startBtn = document.getElementById('start-btn');
const pauseBtn = document.getElementById('pause-btn');
const resumeBtn = document.getElementById('resume-btn');
const restartBtn = document.getElementById('restart-btn');
const playAgainBtn = document.getElementById('play-again-btn');
const scoreDisplay = document.getElementById('score');
const timeDisplay = document.getElementById('time');
const finalScoreDisplay = document.getElementById('final-score');
const highScoreDisplay = document.getElementById('high-score');
const endHighScoreDisplay = document.getElementById('end-high-score');

// 游戏状态
let score = 0;
let time = 30;
let gameInterval;
let timerInterval;
let isPaused = false;
let blocks = [];
let blockInterval;
let highScore = localStorage.getItem('blockCollectorHighScore') || 0;
let difficulty = 1;

// 更新最高分显示
highScoreDisplay.textContent = highScore;
endHighScoreDisplay.textContent = highScore;

// 颜色数组 - 用于方块的随机颜色
const colors = [
    'linear-gradient(45deg, #ff6b6b, #ee5253)',
    'linear-gradient(45deg, #4ecdc4, #45b7d1)',
    'linear-gradient(45deg, #ffda79, #ffb142)',
    'linear-gradient(45deg, #a393eb, #7868e6)',
    'linear-gradient(45deg, #ffaaa5, #ff8b94)'
];

// 开始游戏
function startGame() {
    // 重置游戏状态
    score = 0;
    time = 30;
    difficulty = 1;
    blocks = [];
    scoreDisplay.textContent = score;
    timeDisplay.textContent = time;
    
    // 切换屏幕
    startScreen.classList.add('hidden');
    gameScreen.classList.remove('hidden');
    
    // 清除游戏区域
    gameArea.innerHTML = '';
    
    // 开始生成方块
    startGeneratingBlocks();
    
    // 开始计时
    startTimer();
}

// 生成方块
function generateBlock() {
    if (isPaused) return;
    
    // 创建方块元素
    const block = document.createElement('div');
    block.classList.add('block');
    
    // 随机属性
    const size = Math.floor(Math.random() * 30) + 30; // 30-60px
    const color = colors[Math.floor(Math.random() * colors.length)];
    const left = Math.floor(Math.random() * (gameArea.offsetWidth - size));
    const top = Math.floor(Math.random() * (gameArea.offsetHeight - size));
    
    // 设置方块样式
    block.style.width = `${size}px`;
    block.style.height = `${size}px`;
    block.style.background = color;
    block.style.left = `${left}px`;
    block.style.top = `${top}px`;
    
    // 随机旋转角度增加视觉变化
    const rotation = Math.floor(Math.random() * 15) - 7; // -7到7度
    block.style.transform = `rotate(${rotation}deg)`;
    
    // 添加点击事件
    block.addEventListener('click', () => clickBlock(block));
    
    // 添加到游戏区域
    gameArea.appendChild(block);
    blocks.push(block);
    
    // 设置方块消失时间（随难度增加而缩短）
    const lifeTime = 2000 - (difficulty * 100); // 2000ms到1000ms
    const minLifeTime = 500; // 最小生命周期，防止太快无法点击
    
    setTimeout(() => {
        if (blocks.includes(block)) {
            removeBlock(block, false);
        }
    }, Math.max(lifeTime, minLifeTime));
}

// 开始生成方块
function startGeneratingBlocks() {
    // 初始间隔时间
    let intervalTime = 1000;
    
    // 生成方块
    generateBlock();
    
    // 设置生成方块的间隔（随难度增加而缩短）
    blockInterval = setInterval(() => {
        if (!isPaused) {
            generateBlock();
            
            // 每得10分增加一次难度
            if (score % 10 === 0 && score > 0) {
                difficulty = Math.floor(score / 10) + 1;
                intervalTime = Math.max(300, 1000 - (difficulty * 50)); // 最小300ms
                clearInterval(blockInterval);
                
                // 更新生成间隔
                blockInterval = setInterval(() => {
                    if (!isPaused) generateBlock();
                }, intervalTime);
            }
        }
    }, intervalTime);
}

// 点击方块
function clickBlock(block) {
    if (isPaused) return;
    
    // 增加分数
    const points = Math.floor(10 - (block.offsetWidth / 10)); // 小方块分数更高
    score += points;
    scoreDisplay.textContent = score;
    
    // 显示得分动画
    showPointPopup(block, points);
    
    // 通知 uni-app 得分更新
    if (typeof notifyGameEvent === 'function') {
        notifyGameEvent('scoreUpdate', {
            score: score,
            points: points,
            gameType: 'blockCollector'
        });
    }
    
    // 移除方块
    removeBlock(block, true);
}

// 显示得分动画
function showPointPopup(block, points) {
    const popup = document.createElement('div');
    popup.classList.add('point-popup');
    popup.textContent = `+${points}`;
    popup.style.left = `${parseInt(block.style.left) + block.offsetWidth / 2}px`;
    popup.style.top = `${parseInt(block.style.top) + block.offsetHeight / 2}px`;
    gameArea.appendChild(popup);
    
    // 动画结束后移除
    setTimeout(() => {
        popup.remove();
    }, 500);
}

// 移除方块
function removeBlock(block, isClicked) {
    // 如果是点击的，添加消失动画
    if (isClicked) {
        block.classList.add('fade-out');
        setTimeout(() => {
            block.remove();
        }, 300);
    } else {
        block.remove();
    }
    
    // 从数组中移除
    blocks = blocks.filter(b => b !== block);
}

// 开始计时
function startTimer() {
    timerInterval = setInterval(() => {
        if (!isPaused) {
            time--;
            timeDisplay.textContent = time;
            
            // 时间到，游戏结束
            if (time <= 0) {
                endGame();
            }
        }
    }, 1000);
}

// 暂停游戏
function pauseGame() {
    isPaused = true;
    gameScreen.classList.add('hidden');
    pauseScreen.classList.remove('hidden');
}

// 继续游戏
function resumeGame() {
    isPaused = false;
    pauseScreen.classList.add('hidden');
    gameScreen.classList.remove('hidden');
}

// 结束游戏
function endGame() {
    // 清除所有定时器
    clearInterval(gameInterval);
    clearInterval(timerInterval);
    clearInterval(blockInterval);
    
    // 检查是否是最高分
    if (score > highScore) {
        highScore = score;
        localStorage.setItem('blockCollectorHighScore', highScore);
        highScoreDisplay.textContent = highScore;
        endHighScoreDisplay.textContent = highScore;
    }
    
    // 更新结束界面
    finalScoreDisplay.textContent = score;
    
    // 通知 uni-app 游戏结束
    if (typeof notifyGameEvent === 'function') {
        notifyGameEvent('gameEnd', {
            score: score,
            highScore: highScore,
            gameType: 'blockCollector'
        });
    }
    
    // 切换屏幕
    gameScreen.classList.add('hidden');
    endScreen.classList.remove('hidden');
}

// 事件监听
startBtn.addEventListener('click', startGame);
pauseBtn.addEventListener('click', pauseGame);
resumeBtn.addEventListener('click', resumeGame);
restartBtn.addEventListener('click', startGame);
playAgainBtn.addEventListener('click', startGame);

// 窗口大小变化时重新计算游戏区域
window.addEventListener('resize', () => {
    // 移除所有方块，游戏会自动生成新的
    blocks.forEach(block => block.remove());
    blocks = [];
});
